// pages/my/productOrder-detail/productOrder-detail.js
const controllers = require('../../controllers/ControllerMy').controller;
const Controller = require("../../controllers/Controller").controller

const app = getApp()

function InitTime(endtime) {
  var dd, hh, mm, ss = null;
  var time = (new Date(endtime.replace(/-/g, '/')).getTime() - new Date().getTime()) / 1000;
  if (time <= 0) {
    return '结束'
  } else {
    dd = Math.floor(time / 60 / 60 / 24);
    hh = Math.floor((time / 60 / 60) % 24);
    mm = Math.floor((time / 60) % 60);
    ss = Math.floor(time % 60);
    var str = dd + "天" + hh + ":" + mm + ":" + ss;
    return str;
  }
}
Page({

  /**
   * 页面的初始数据
   */
  data: {
    globalStype: '',
    detail: {},
    imgurl: '',
    orderNo: 0,
    goodsId: 0,
    payType: '',
    all: '',
    isshow: false,
    singleord: '',
    buttons: [{
      text: '取消'
    }, {
      text: '确定'
    }],
    downtime: '',
    timer: '',
    shopId: ''
  },
  //按钮事件
  tapDialogButton(e) {
    console.log(e);
    if (e.detail.index == 0) {
      this.setData({
        isshow: false
      })
    } else {
      this.cancelOrder()
      this.setData({
        isshow: false
      })
    }
  },
  //显示取消确定弹窗
  toshow(e) {
    this.setData({
      isshow: true,
      singleord: e.currentTarget.id
    })
  },
  //取消订单
  cancelOrder(e) {
    controllers.cancelOrder({
      shopId: app.globalData.shopId,
      orderNo: this.data.singleord,
      type: 1
    }).then(res => {
      wx.showToast({
        title: '取消成功',
        icon: 'none'
      })
      setTimeout(function () {
        // wx.navigateTo({
        //   url: '/pages/my/product-order/product-order',
        // })
        wx.navigateBack({
          complete: (res) => {},
        })
      }, 1000)
    })
  },

  //跳转到评论页面
  toComment(e) {
    wx.navigateTo({
      url: '/pages/my/service-comment/service-comment?id=' + e.currentTarget.id + '&type=' + e.currentTarget.dataset.type + '&from=' + e.currentTarget.dataset.from,
    })
  },

  //申请核销
  applyWriteOff() {
    let that = this
    wx.showModal({
      title: '提示',
      content: '是否完成订单或申请核销该商品',
      success(res) {
        if (res.confirm) {
          that.writeOff()
        }
      }
    })
  },

  writeOff() {
    let value = {}
    value.shopId = wx.getStorageSync('shopId')
    value.orderNo = this.data.orderNo
    controllers.applyWriteOff(value).then(res => {
      wx.showToast({
        icon: "none",
        title: '操作成功',
      })
      this.getOrderDetail()
    })
  },
  contactService() {
    wx.navigateTo({
      url: '/pages/my/vip/vip_feedBack/index?id=0',
    })
  },
  // 复制订单
  copyOrder() {
    const detail = this.data.detail
    const orderNo = this.data.orderNo
    const money = detail.type == 4 ? (detail.integral + '积分') : (detail.money + '元')

    const data = `下单用户:${detail.account.nick},联系方式:${detail.account.mobile},收货地址:${detail.address ?? '到店自取'},订单号:${orderNo},跟单员工:${detail.shopAccountNick},实付款:${money}`

    wx.setClipboardData({
      data
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      globalStype: app.globalData.globalStype
    })
    this.setData({
      imgurl: app.globalData.IMG_URL
    })
    this.setData({
      orderNo: options.id
    })
    if (wx.getStorageSync('shopId')) {
      this.setData({
        shopId: wx.getStorageSync('shopId')
      })
      app.globalData.shopId = wx.getStorageSync('shopId')
    }
    if (options.shopId) {
      this.setData({
        shopId: options.shopId
      })
      app.globalData.shopId = options.shopId
      wx.setStorageSync('shopId', options.shopId)
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    //获取订单详情
    let shopId = this.data.shopId || app.globalData.shopId
    if (wx.getStorageSync('usertoken')) {
      this.getOrderDetail()
      // this.GetLogin()
    } else {
      app.GetLogin()
    }
    app.usertokenReadyCallback = res => {
      if (res.data.sessionId) {
        this.getOrderDetail()
      }
    }
    // controllers.getOrderDetail({
    //   shopId: shopId,
    //   orderNo: this.data.orderNo,
    //   type: 1
    // }).then(res => {
    //   let all = 0;
    //   res.data.goodsList.forEach(function (item, index) {
    //     all = all + item.num
    //   })

    //   this.setData({
    //     detail: res.data,
    //     orderNo: this.data.orderNo,
    //     all: all
    //   })
    //   if (this.data.detail.marketAccountList && this.data.detail.marketAccountList[0].endTime) {
    //     this.setData({
    //       timer: setInterval(() => {
    //         this.data.downtime = InitTime(this.data.detail.marketAccountList[0].endTime.replace(/-/g, '/'))
    //         this.setData({
    //           downtime: this.data.downtime
    //         })
    //       }, 1000)
    //     })
    //   }
    //   if (res.data.payType == 0) {
    //     this.setData({
    //       payType: '支付宝'
    //     })
    //   } else if (res.data.payType == 1) {
    //     this.setData({
    //       payType: '微信'
    //     })
    //   } else if (res.data.payType == 2) {
    //     this.setData({
    //       payType: '余额'
    //     })
    //   } else if (res.data.payType == 3) {
    //     this.setData({
    //       payType: '积分'
    //     })
    //   } else {
    //     this.setData({
    //       payType: '现金'
    //     })
    //   }
    // })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    clearInterval(this.data.timer)
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  // onShareAppMessage: function () {

  // },
  backIndex(e) {
    let page = getCurrentPages()
    let shopId = this.data.shopId
    console.log(page.length)
    if (page.length <= 1) {
      wx.redirectTo({
        url: '/pages/Index/Index?shopId=' + shopId,
      })
    }
  },

  //没有token时执行登录函数，后执行请求
  GetLogin(flag) {
    let that = this;
    if (flag == undefined || flag) {
      wx.showLoading({
        title: '登录中...',
        mask: true
      });
    }
    wx.login({
      success: res => {
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
        Controller.appletLogin({
          code: res.code
        }).then(result => {
          console.log(result.data)
          app.globalData.sessionKey = result.data.sessionKey
          wx.setStorageSync('usertoken', result.data.sessionId)
          that.getOrderDetail()
          app.globalData.openId = result.data.openId
          if (flag == undefined || flag) {
            wx.hideLoading();
          }
        }).catch(res => {
          wx.hideLoading();
        })

      }
    });
  },

  //获取订单详情
  getOrderDetail() {
    controllers.getOrderDetail({
      shopId: wx.getStorageSync('shopId'),
      orderNo: this.data.orderNo,
      type: 1
    }).then(res => {
      let all = 0;
      res.data.goodsList.forEach(function (item, index) {
        all = all + item.num
      })

      this.setData({
        detail: res.data,
        orderNo: this.data.orderNo,
        all: all
      })
      if (this.data.detail.marketAccountList && this.data.detail.marketAccountList[0].endTime) {
        this.setData({
          timer: setInterval(() => {
            this.data.downtime = InitTime(this.data.detail.marketAccountList[0].endTime.replace(/-/g, '/'))
            this.setData({
              downtime: this.data.downtime
            })
          }, 1000)
        })
      }
      if (res.data.payType == 0) {
        this.setData({
          payType: '支付宝'
        })
      } else if (res.data.payType == 1) {
        this.setData({
          payType: '微信'
        })
      } else if (res.data.payType == 2) {
        this.setData({
          payType: '余额'
        })
      } else if (res.data.payType == 3) {
        this.setData({
          payType: '积分'
        })
      } else {
        this.setData({
          payType: '现金'
        })
      }
    })
  }
})